'use strict';
module.exports = {
	/**
	 * 新增账本关联关系
	 * @url client/accountbook/kh/addUserRelationBook 前端调用的url参数地址
	 * data 请求参数
	 * @params {String} accountBookName  账本名称
	 * @params {String} accountType  账本类型
	 * @params {String} remarks  账本说明
	 */
	main: async (event) => {
		let { data = {}, userInfo, util, originalParam } = event;
		let { customUtil, config, pubFun, vk, db, _ } = util;
		let { uid, bookId } = data && data;
		let res = { code : 0, msg : '加入成功' };
		// 业务逻辑开始-----------------------------------------------------------
		if(pubFun.isEmpty(bookId)){
			return { code : 1001, msg : '参数错误' };
		}
		
		// 查询账本是否存在
		let accountBookInfo = await vk.daoCenter.accountBookDao.findById(bookId);
		if(pubFun.isEmpty(accountBookInfo)) {
			return { code : 1002, msg : '账本不存在' };
		}
		
		const paramUtil = vk.require("service/client/accountbook/util/paramUtil");
		
		// 开启事务
		const transaction = await vk.baseDao.startTransaction();
		try {
			const _data = await paramUtil.initBaseInsertParam({uid,bookId});
			const userRelationBookId = await vk.daoCenter.userRelationBookDao.add({
				db: transaction,
				dataJson: _data
			});
			if (userRelationBookId == null) {
				throw new Error("新增账本用户关联关系失败");
			}
			// 提交事务
			await transaction.commit();
		} catch (err) {
			// 事务回滚
			await vk.baseDao.rollbackTransaction({db: transaction,err});
			console.error(`transaction error`, err)
		    return {
		      code: -1,
		      msg: "数据库写入异常,事务已回滚",
		      err: {
		        message: err.message,
		        stack: err.stack
		      },
			}
		}
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}
